/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cirnoworks.framework.server;

/**
 *
 * @author Cloudee
 */
public class ServerContenter implements Runnable {

    public static final int CLOSED = 0;
    public static final int STARTING = 1;
    public static final int RUNNING = 2;
    public static final int CLOSING = 3;
    private final Object statLock = new Object();
    private volatile int stat;
    private Server server;

    public int getStat() {
        return stat;
    }

    public ServerContenter(Server server) {
        this.server = server;
    }

    public void start() {
        synchronized (statLock) {
            if (stat != CLOSED) {
                throw new IllegalStateException(String.valueOf(stat));
            }
            stat = STARTING;
            server.prepareSync();
            new Thread(this).start();
        }
    }

    public void stop(boolean wait) {
        synchronized (statLock) {
            if (stat != RUNNING) {
                throw new IllegalStateException(String.valueOf(stat));
            }
            stat = CLOSING;
            server.forceShutdown();
            try {
                while (wait) {
                    if (server.isShutdown()) {
                        break;
                    }
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
            }

        }
    }

    public void run() {
        //Thread current = Thread.currentThread();
        try {
            synchronized (statLock) {
                if (stat != STARTING) {
                    throw new IllegalStateException(String.valueOf(stat));
                }
                server.prepareASync();
                stat = RUNNING;
            }

            while (stat == RUNNING) {
                server.mainLoop();
            }

            server.cleanup();
        } finally {
            synchronized (statLock) {
                stat = CLOSED;
            }
        }
    }
}
